package com.example.nettyudp.server;

import com.example.nettyudp.vo.MessageVo;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author FDJ,
 * @date 2020/5/26,
 * @time 9:35
 */
@Slf4j
@Component
public class NettyServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Autowired
    NettyBean nettyBean;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {
        System.out.println("channelRead0执行");
        nettyBean.setChannel(datagramPacket.sender().getHostName(), ctx);

        /**
         * 接收参数request
         */
        String req = datagramPacket.content().toString(CharsetUtil.UTF_8);//通过content()来获取消息内容
        MessageVo messageVo = new MessageVo(req);
        System.out.println(req);


        /**
         * 返回参数reponse
         */
        String message = "SIP OK\r\n" +
                "SIP/2.0 200 OK\r\n" +
                "Via: SIP/2.0/UDP 192.168.2.128:8899;rport=5060;received=192.168.2.128;branch=z9hG4bKPjc173d8ae3c3c43d4b054635c3508ff03\r\n" +
                "From: <sip:31011780002000000002@192.168.2.128:9090>;tag=4352b53118cf46529416b2acabae848b\r\n" +
                "To: <sip:31011780002000000002@192.168.2.128:9090>;tag=667780755\r\n" +
                "CSeq: 32862 REGISTER\r\n" +
                "Call-ID: c9b60272b2bd498eb80708ef254223b7\r\n" +
                "User-Agent: LiveGBS v200418\r\n" +
                "Contact: <sip:31011700002000000002@192.168.2.128:9090>\r\n" +
                "Content-Length: 0\r\n" +
                "Date: 2020-04-27T12:28:32.979\r\n" +
                "Expires: 3000";


        byte[] bytes = message.getBytes("UTF-8");
        DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), datagramPacket.sender());
        //向客户端发送消息
        ctx.writeAndFlush(data);
    }
}
